package com.ldu.exam.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ldu.exam.model.AccountModel;
import com.ldu.exam.model.AccountModelForm;
import com.ldu.exam.model.ClaModel;
import com.ldu.exam.model.ExamModel;
import com.ldu.exam.model.RoleModel;
import com.ldu.exam.service.AccountService;

import sun.misc.BASE64Encoder;


@RequestMapping("/accounts") 
@RestController
public class AccountController 
{
	@Autowired private AccountService service ;
	
	/**
	 * 查询全部账户信息
	 * @param page 当前页
	 * @param size 每页显示数目
	 * @return	全部账户信息
	 */
	@GetMapping()
	public Page<AccountModel> findAll(@PageableDefault(size=20) Pageable page)
	{
		return this.service.findAll( page) ;
	}
	
	@GetMapping(value="/noPage")
	public Object findAllNoPage()
	{
		return this.service.findAllNoPage();
	}
	
	@GetMapping(value="/students")
	public Page<AccountModel> findStudents(@RequestParam( required=false, defaultValue="0")  int page,
			 @RequestParam( required=false, defaultValue="20") int size) 
	{
		return (Page<AccountModel>) this.service.findStudents(page, size);
	}
	
	@GetMapping(value="/teachers")
	public Page<AccountModel> findTeachers(@RequestParam( required=false, defaultValue="0")  int page,
			 @RequestParam( required=false, defaultValue="20") int size)
	{
		return (Page<AccountModel>) this.service.findTeachers(page, size);
	}
	
	@GetMapping(value="/students/class")
	public Page<AccountModel> findStudentsByClassId(@RequestParam("classId") String classId,
			@RequestParam( required=false, defaultValue="0")  int page,
			 @RequestParam( required=false, defaultValue="20") int size)
	{
		return (Page<AccountModel>) this.service.findStudentsByClassId(classId, page, size);
	}
	
	@GetMapping(value="/students/nickname")
	public Page<AccountModel> findStudentsByNickName(@RequestParam("nickname") String nickname,
			@RequestParam( required=false, defaultValue="0")  int page,
			 @RequestParam( required=false, defaultValue="20") int size)
	{
		return (Page<AccountModel>) this.service.findStudentsByNickname(nickname, page, size);
	}
	
	@GetMapping(value="/teachers/class")
	public Page<AccountModel> findTeachersByClassId(@RequestParam("classId") String classId,
			@RequestParam( required=false, defaultValue="0") int page,
			@RequestParam( required=false, defaultValue="20") int size)
	{
		return (Page<AccountModel>) this.service.findTeachersByClassId(classId, page, size);
	}
	
	@GetMapping(value="/teachers/nickname")
	public Page<AccountModel> findTeachersByNickName(@RequestParam("nickname") String nickname,
			@RequestParam( required=false, defaultValue="0")  int page,
			 @RequestParam( required=false, defaultValue="20") int size)
	{
		return (Page<AccountModel>) this.service.findTeachersByNickname(nickname, page, size);
	}
	/**
	 * 根据id查询账户信息
	 * @param id 账户ID
	 * @return
	 */
	@GetMapping("/{id}")
	public Object find( @PathVariable String id )
	{
		return this.service.find( id);
	}
	
	/**
	 * 删除账户
	 * @param id
	 */
	@DeleteMapping("/{id}")
	public Object delete( @PathVariable String id)
	{
		this.service.delete(id);
		return ResponseEntity.noContent().build();
	}
	
	/**
	 * 新增账户
	 * @param model
	 * @return
	 */
	@PostMapping()
	public Object save( @RequestBody AccountModel model,@RequestParam String roleId)
	{
		AccountModel accountModel = this.service.save(model,roleId);
		if(accountModel == null)
		{	
			return null;
		}
		return accountModel;
	}
	
	/**
	 * 修改账户信息
	 * @param id
	 * @param model
	 * @return
	 */
	@PutMapping("/{id}")
	public Object patch( @PathVariable String id ,  @RequestBody AccountModel model)
	{
		return this.service.patch(id, model);
	}
	
	@PutMapping("/{id}/cla")
	public Object updateTeacherCla( @PathVariable String id ,@RequestBody Set<ClaModel> cla)
	{
		return this.service.putCla(id, cla);
	}
	
	@PutMapping("/{id}/studentCla")
	public Object updateStudentCla( @PathVariable String id , @RequestParam String claId)
	{
		return this.service.updateStudentCla(id, claId);
	}
	
	/**
	 * 账户分配角色
	 * @param id
	 * @param roles
	 * @return
	 */
	@PutMapping("/{id}/roles")
	public Object putRoles( @PathVariable String id ,  @RequestBody Set<RoleModel> roles)
	{
		return this.service.putRoles( id, roles) ;
	}
	
	@PutMapping(value="/exams")
	public Object putExams(@RequestParam List<String> userIds,@RequestParam String examId)
	{
		ExamModel em = new ExamModel();
		em.setId(examId);
		return this.service.putExams(userIds, em);
	}
	/**
	 * 根据名称查询账户信息
	 * @param name
	 * @param page
	 * @return
	 */
	@GetMapping(params="name")
	public  Page<AccountModel> findByName( @RequestParam String name, 
										 	@PageableDefault(size=20) Pageable page)
	{
		
		return this.service.findByNameContaining( name, page) ;
	}
	
	/**
	 * 账户登录
	 * @param username
	 * @param password
	 * @return
	 */
	@GetMapping(value= {"/authentication"},params= {"password","username"})
	public ResponseEntity<?> authenticate( @RequestParam String username , @RequestParam String password)
	{
		return this.service.authenticate( username, password) ;
	}
	
	
	/**
	 * 上传头像
	 */
	@PostMapping("uploadImg")
	public Object uploadImg (@RequestParam MultipartFile file,HttpServletRequest request)
	{
		String realPath = request.getSession().getServletContext().getRealPath("/");
		if(file.isEmpty()) return false;
		String fileName = file.getOriginalFilename();
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		fileName = UUID.randomUUID()+suffixName;
		File dest = new File(realPath+fileName);
		System.out.println(realPath+fileName);
		try {
			file.transferTo(dest);
			return fileName;
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return fileName;
	}
	
	@PostMapping("upload")
	public Object upload (@RequestParam MultipartFile file,HttpServletRequest request)
	{
		File file1 = null;
		InputStream is = null;
		byte[] data =null;
		String img_path = "";
		String base64 = "";
		try {
			file1 = File.createTempFile("tmp", null);
			file.transferTo(file1);
			img_path = file1.getPath();

			is = new FileInputStream(img_path);          
            data = new byte[is.available()];  
            is.read(data);
            base64 = new BASE64Encoder().encode(data);
			file1.deleteOnExit();  
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return base64;
	}
	
	/**
	 * 修改密码
	 */
	@GetMapping(value="/{id}/password")
	public Object updatePwd1(@PathVariable String id,
			@RequestParam String oldPass,
			@RequestParam String newPass) 
	{
		return this.service.updatePwd11(id, oldPass, newPass);
	}
	
	/**
	 * 检测是否有昵称
	 */
	@GetMapping(value="/{id}/nickname")
	public Object hadNickname(@PathVariable String id)
	{
		return this.service.hadNickname(id);
	}
}
